package cn.com.open.itembank.service.impl;

import cn.com.open.itembank.dto.AsyncRule;
import cn.com.open.itembank.service.GenerateCreateTestPaper;
import cn.com.open.itembank.utils.JsonUtil;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@Component
public class AsyncTask{

    @Autowired
    private GenerateCreateTestPaper generateCreateTestPaperUtil;

    /**
     * 异步组卷
     * @param asyncRule 异步组卷传输模型
     */
    @Async
    public void asyncGenerateCreateTestPaper(AsyncRule asyncRule) throws UnsupportedEncodingException {

        String paperidStr = (String) generateCreateTestPaperUtil.generateCreateTestPaper(asyncRule).getData();
        final String CONTENT_TYPE_TEXT_JSON = "text/json";

        Map<String,Object> map = new HashMap<>();
        map.put("Rid", asyncRule.getRuleID());
        map.put("Count", asyncRule.getPaperCount());
        map.put("Pid", paperidStr);
        String gsonStr = JsonUtil.getJsonWithoutDisableHtmlEscaping(map);
        HttpPost httpPost = new HttpPost(asyncRule.getUrl());
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.setHeader("appkey", asyncRule.getAppKey());
        httpPost.setHeader("appsecret", "1");

        StringEntity se = new StringEntity(gsonStr);
        se.setContentType(CONTENT_TYPE_TEXT_JSON);
        httpPost.setEntity(se);
    }


}
